package de.lulusoft.anothertorrent.gui.commands;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

import de.lulusoft.anothertorrent.core.rtorrent.File;
import de.lulusoft.anothertorrent.gui.AnotherTorrentGui;

public class FileSetPriorityCommand implements IHandler {
	
	public static final String ID = "de.lulusoft.anothertorrent.gui.commands.FileSetPriorityCommand";

	public static final String P_FILE = "fileParameter";
	public static final String P_PRIORITY = "priorityParameter";
	
	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
	}

	@Override
	public void dispose() {
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		if (event.getTrigger() instanceof File)
		{
			File f = (File)event.getTrigger();
			Long val = Long.parseLong(event.getParameter(P_PRIORITY));
			try {
				// Send cmd to server
				f.getTorrent().getServer().getRTorrentManager()
					.fileSetPriority(f.getTorrent().getHash(), f.getIndex(), val);
				f.getTorrent().getServer().getRTorrentManager()
					.torrentUpdatePriorities(f.getTorrent().getHash());
			} catch (Exception e) {
				IStatus status = new Status(IStatus.ERROR, 
						AnotherTorrentGui.PLUGIN_ID, "Could not set file priority", e);
				AnotherTorrentGui.getDefault().getLog().log(status );
				e.printStackTrace();
			}
			
			// Change local cached data to reflect the changes immediately
			f.setPriority(val);
		}
		return null;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	@Override
	public boolean isHandled() {
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
	}

}
